#include <SoftwareSerial.h> 
#include <dht11.h>
#include <math.h>
#include <ArduinoJson.h>

dht11 DHT11; //定义温湿度传感器
int FLAMEPIN = A0; //指定模拟端口A0
int MQ2 = A1; //指定模拟端口A1
int speakerPin = 5;//控制喇叭的引脚
int bluePin = 6;  // B蓝色LED 控制引脚 
int greenPin = 7;  // G绿色LED 控制引脚 
int redPin = 8;  // R 红色LED 控制引脚 
int DHT11PIN = 9; //温湿度传感器引脚

//声明临时变量
int mqval = 0; //气体浓度
int humidity = 0; //湿度
int flameval = 0; //火焰（红外线）
int temval = 0; //温度

char msg[16];

SoftwareSerial mySerial(2,3);
char res[20];

bool testOpen = false;// 测试警报控制 是否打开警报
bool closeWarn = false;// 关闭警报
bool normalOpen = true;// 启动正常警报


void setup()
{
  pinMode(MQ2,INPUT);
  pinMode(redPin, OUTPUT); 
  pinMode(greenPin, OUTPUT); 
  pinMode(bluePin, OUTPUT); 
  pinMode(FLAMEPIN,INPUT);
  pinMode(speakerPin,OUTPUT);
  Serial.begin(119200);
  Serial.println("DHT11 TEST PROGRAM ");
  Serial.print("LIBRARY VERSION: ");
  Serial.println(DHT11LIB_VERSION);
  Serial.println();
  
  //软件串口波特率
  mySerial.begin(9600);
}

// 通过热敏电阻与采样电阻的一系列值计算出温度
double Thermister(int RawADC) 
{ 
   double Temp; 
   Temp = log(((10240000/RawADC) - 10000)); 
   Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp ); 
   Temp = Temp - 273.15;            // Convert Kelvin to Celcius 
   return Temp; 
} 

void loop()
{
  int chk = DHT11.read(DHT11PIN); //读取DHT11
  mqval = analogRead(MQ2); //读取A1口的电压值并赋值到mqval
  humidity = (int)DHT11.humidity; //读取湿度值
  flameval = analogRead(FLAMEPIN); //读取火焰传感器的模拟值
  temval = (int)Thermister(analogRead(2)); //读取热敏电阻温度值

  Serial.print("湿度: ");
  Serial.print(humidity);
  Serial.println("%");
  Serial.print("温度: ");
  Serial.print(temval);
  Serial.println("摄氏度");
  Serial.print("气体浓度值: ");
  Serial.println(mqval);
  Serial.println(flameval); //读取火焰传感器的值
  Serial.println();

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& object = jsonBuffer.createObject();
  object["t"] = temval;
  object["h"] = humidity;
  object["s"] = 10;

  if(mqval>830 || temval>60 || flameval>700){
     if (mqval>830){
       object["s"] = 3;
     }
     if (temval>60){
        object["s"] = 1;
     }

     if (flameval>700){
        object["s"] = 2;
     }
  }
  object.printTo(mySerial);
  
  
  if(mySerial.available()>0){
      // {"t":30,"h":50,"m":40,"s":0}
    Serial.println("has data");
      memset(res, 0, 20);      //清空
      int length = mySerial.readBytesUntil('}',res, 20);
      while(mySerial.available()>0){
        char c = mySerial.read();
      }
     
      res[length] = '}';
      res[++length] = 0;

      Serial.println(res);
      
      DynamicJsonBuffer jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(res);

      // 解析数据
      if (!root.success()) {
        Serial.println("JSON parsing failed!");
      } else {
         Serial.println("JSON parsing success!");
         if (root.containsKey("t")){
             strcpy(msg, root["t"]);
             if (strcmp(msg,"off")==0){
                 closeWarn = true;
                 testOpen = false;
                 normalOpen = false;
             }
      
             if (strcmp(msg,"on")==0){
                closeWarn = false;
                testOpen = true;
                normalOpen = false;
             }

             if (strcmp(msg,"on1")==0){
                  // 打开
                closeWarn = false;
                testOpen = false;
                normalOpen = true;
             }
         }
      }
   }

  if (closeWarn) {
     normal();
  } else {
     if (testOpen){
         warn();
     }else if(normalOpen){
          if(mqval>830 || temval>60 || flameval>700){
            warn();
          }else{
            normal();
          }
     }
  }

  delay(1000);
}

//触发警报
void warn(){
  color(255, 0, 0);
  digitalWrite(speakerPin,HIGH);
}

//正常状态
void normal(){
  color(0, 200, 100);
  digitalWrite(speakerPin,LOW);
}

void color (unsigned char red, unsigned char green, unsigned char blue)  //颜色控制函数 
{    
  analogWrite(redPin, red);   
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue); 
}
